#include <iostream>
#include <assert.h>
#include <stdio.h>

#include "cmdline.h"
#include "detect_cliques.h"
#include "gzstream.h"

static const char *REVISION = "$Revision: 1.9 $";

int main(int argc, char **argv)
{
	std::cout << "Super-tagging feature detection: "
			  << "Copyright 2006 Phil Blunsom\n";
	std::cout << REVISION << '\n' << std::endl;

	// process cmdline
	boost::shared_ptr<Parameters> args_info(new Parameters);
	if (align_parser2(argc, argv, args_info.get(), 1, 1, 0) != 0)
		return EXIT_FAILURE;
	if (args_info->conf_file_given && 
		align_parser_configfile(args_info->conf_file_arg, args_info.get(), 1, 0, 1) 
		!= 0)
		return EXIT_FAILURE;

	std::cout << "Loading features" << std::endl;
	CliqueDetectorPtr clique_detector(new CliqueDetector(args_info));
	std::string tmp_filename = std::string(".") + args_info->output_arg;
	ogzstream clique_file(tmp_filename.c_str());

	int i=0;
	std::cout << "Writing cliques" << std::endl;
	int start = args_info->start_sentence_arg;
	int end = -1;
	if (args_info->sentences_given)
		end = start + args_info->sentences_arg;
	while(true)
	{
		++i;
		if (i < start) continue;
		if (end >= 0 && i > end)
				break;
		if (i % 100 == 0)
		{
			std::cout << '.';
			std::cout.flush();
		}
		if (i % 5000 == 0)
			std::cout << " " << i << std::endl;

		CliqueDetector::EventPtr e = clique_detector->next();
		if (e.get() == 0) break;
		e->crf_write(clique_file);
	}
	std::cout << std::endl;

	// write the header info
//		  assert(i < 10^10 && clique_detector->num_features() < 10^10);
//		  clique_file.seekp(header_ptr);
//		  clique_file << i-1-start << ' ' << clique_detector->num_features();
	clique_file.close();

	igzstream tmp_file(tmp_filename.c_str());
	clique_file.open(args_info->output_arg);
	clique_file << "SEMI_CRF\n";
	clique_file << i-1-start << ' ' 
				<< clique_detector->num_features() << "\n";
	char c;
	while(tmp_file.get(c))
		clique_file.put(c);
	clique_file.close();
	tmp_file.close();
	remove(tmp_filename.c_str());

//		  // remember where the head should go and leave some space
//		  int header_ptr = clique_file.tellp();
//		  clique_file << "						\n";

	return 0;
}
